const PREFIX  = 'zw'

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function unit(v, defaultUnit = 'px') {
  // console.log(isNumeric(v))
  if (isNumeric(v)) {
    return v + defaultUnit
  } else {
    return v
  }
}

class XyRow extends HTMLElement {

  static get observedAttributes() { return ['gutter', 'row-gutter'] }

  constructor() {
    super();
    const shadowRoot = this.attachShadow({ mode: 'open' });
    shadowRoot.innerHTML = `
        <style>
        :host {
            --gutter:${unit(this.gutter)};
            display:grid;
            grid-template-columns:repeat(24,1fr);
            grid-gap: var(--row-gutter, var(--gutter)) var(--gutter,0);
        }
        </style>
        <slot></slot>
        `
  }

  get gutter() {
    return this.getAttribute('gutter');
  }

  set gutter(value) {
    this.setAttribute('gutter', value);
  }

  get rowGutter() {
    return this.getAttribute('row-gutter');
  }

  set rowGutter(value) {
    this.setAttribute('row-gutter', value);
  }

  attributeChangedCallback (name, oldValue, newValue) {
    if (this.shadowRoot) {
      // console.log(name)
      if( name === 'gutter'){
        this.style.setProperty('--gutter',unit(newValue));
      }
      if( name === 'row-gutter'){
        this.style.setProperty('--row-gutter',unit(newValue));
      }
    }
  }

}

if(!customElements.get(PREFIX + '-row')){
  customElements.define(PREFIX + '-row', XyRow);
}

class XyCol extends HTMLElement {

  constructor() {
    super();
    const shadowRoot = this.attachShadow({ mode: 'open' });

    shadowRoot.innerHTML = `
        <style>
        :host {
            grid-column: span 1;
        }
        ${
      Array.from({length:24},(el,i)=>':host([span="'+(i+1)+'"]) {grid-column: span '+(i+1)+'}\n').join('')
    }
        </style>
        <slot></slot>
        `
  }
}

if(!customElements.get(PREFIX + '-col')){
  customElements.define(PREFIX + '-col', XyCol);
}

export default class XyLayout extends HTMLElement {

  constructor() {
    super();
    const shadowRoot = this.attachShadow({ mode: 'open' });
    shadowRoot.innerHTML = `
        <style>
        :host {
            display:flex;
            flex-direction:column;
        }
        :host([row]){
            flex-direction:row;
        }
        :host([column]){
            flex-direction:column;
        }
        :host([expand]){
            flex:1;
        }
        :host([center]:not([center$=Axis])){
            justify-content: center;
            align-items: center;
        }
        :host([center="mainAxis"]){
            justify-content: center;
        }
        :host([center="crosAxis"]){
            align-items: center;
        }

        </style>
        <slot></slot>
        `
  }
}

if(!customElements.get(PREFIX + '-layout')){
  customElements.define(PREFIX + '-layout', XyLayout);
}
